package com.example.sneakerappforme1105;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.sneakerappforme1105.DTO.OrderPostData;
import com.example.sneakerappforme1105.ViewModel.CartViewModel;
import com.example.sneakerappforme1105.adapter.OrderItemAdapter;
import com.example.sneakerappforme1105.bean.Address;
import com.example.sneakerappforme1105.bean.CartItem;
import com.example.sneakerappforme1105.bean.Goods;
import com.example.sneakerappforme1105.bean.Order;
import com.example.sneakerappforme1105.bean.OrderItem;
import com.example.sneakerappforme1105.dao.AddressDao;
import com.example.sneakerappforme1105.dao.CartItemDao;
import com.example.sneakerappforme1105.dao.OrderDao;
import com.example.sneakerappforme1105.dao.OrderItemDao;
import com.example.sneakerappforme1105.util.DateUtil;
import com.example.sneakerappforme1105.util.ImageLoader;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PurcharseActivity extends AppCompatActivity {
    private String TAG = "PurcharseActivity";
    private LinearLayout ll_address;
    private RecyclerView rv_purchaseItem;
//    private LinearLayout ll_goods;
    private AddressDao addressDao;
    private static final int REQUEST_CODE_PAYMENT = 1001;

    // toolbar
    ImageView iv_back;
    TextView tv_title;

    private CartItemDao cartItemDao;
    private OrderDao orderDao;
    private OrderItemDao orderItemDao;
    private Long mUserId; //传入 userId
    private Long mCartId;
    private double total;
    private int pos;
    private CartViewModel cartViewModel;
    private List<CartItem> mCartItemList = new ArrayList<>();
    private HashMap<Long, Goods>mGoodsMap = new HashMap<>();
    private TextView tv_total_price;
    private TextView tv_sum;
    private Long orderId;

    @Override
    protected void onResume() {
        super.onResume();



    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG,"下单页重启");
        setContentView(R.layout.activity_purcharse);
        mUserId = getIntent().getLongExtra("userId",0L);
        mCartId = getIntent().getLongExtra("cartId",0L);
        total = getIntent().getDoubleExtra("total",0);
        pos = getIntent().getIntExtra("pos",0);// 默认是第一个地址
        // 反序列化数据
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mGoodsMap = (HashMap<Long, Goods>) bundle.getSerializable("goodsMap");
            mCartItemList = (List<CartItem>) bundle.getSerializable("cartItemList");
            Log.d(TAG, "接收到 mGoodsMap 大小：" + mGoodsMap.size());
            Log.d(TAG, "接收到 mCartItemList 大小：" + mCartItemList.size());
//            cartViewModel = MainApplication.getInstance().getCartViewModel();
//            cartViewModel.setGoodsMap(mGoodsMap);
//            cartViewModel.setCartItemList(mCartItemList);
        }




        findViewById(R.id.iv_back3).setOnClickListener(view -> {
            Intent intent = new Intent(this,RootActivity.class);// 回到购物车页面
            intent.putExtra("userId",mUserId);
            intent.putExtra("cartId",mCartId);
            intent.putExtra("cartFragment",1);//回到购物车
            startActivity(intent);
        });

        tv_title = findViewById(R.id.tv_title3);
        tv_title.setText("支付订单");

        ll_address = findViewById(R.id.ll_address);

        ll_address.removeAllViews();
        rv_purchaseItem = findViewById(R.id.rv_purchaseItem);
        LinearLayoutManager llm = new LinearLayoutManager(this);
        rv_purchaseItem.setLayoutManager(llm);  // 线性布局

        cartItemDao = MainApplication.getInstance().getAppDatabase().cartItemDao();
        addressDao = MainApplication.getInstance().getAppDatabase().addressDao();
        orderDao = MainApplication.getInstance().getAppDatabase().orderDao();
        orderItemDao = MainApplication.getInstance().getAppDatabase().orderItemDao();



        Log.d(TAG,"mGoodsMap拿到"+mGoodsMap.size());


        Log.d(TAG,"mCartItemList拿到"+mCartItemList.size());

        // 默认选择第一条地址
        List<Address> addressList = addressDao.getAllAddressesByUserId(mUserId);
        Address first = addressList.get(pos);   // 根据地址进行切换
        View addressView = LayoutInflater.from(this).inflate(R.layout.item_address,null);
        TextView tv_address = addressView.findViewById(R.id.tv_address);
        ImageView iv_xg = addressView.findViewById(R.id.iv_xg);
        TextView tv_username = addressView.findViewById(R.id.tv_username);
        TextView tv_tel = addressView.findViewById(R.id.tv_tel);
        Button bt_delAddress = addressView.findViewById(R.id.bt_delAddress);
        bt_delAddress.setVisibility(View.GONE);

        tv_address.setText(first.getDetailedAddress());
        tv_username.setText(first.getUsername());
        tv_tel.setText(first.getPhoneNumber());
        ll_address.addView(addressView);

        orderId = getIntent().getLongExtra("orderId",0L);
        Log.d(TAG,"订单号为"+orderId);
        // 购物车传过来 total 总金额
        Order orderToPay = new Order(mUserId,"pay",total, DateUtil.getNowDateTime(""),first.getDetailedAddress()+" "+first.getUsername()+" "+first.getPhoneNumber(),"pay");

        if(orderId==0) {
            orderId = orderDao.insertOneOrder(orderToPay); // 根据订单Id,创建订单项目
            orderToPay.setOrderId(orderId);
        }else{
            orderToPay.setOrderId(orderId);
        }

        List<OrderItem> orderItems = new ArrayList<>();
        for(CartItem item: mCartItemList){  // 订单相关的订单项
            if(item.getIsChecked()==1){
                // 是已经勾选上的
                OrderItem o = new OrderItem(orderId,item.getGoodsId(),item.getNum(),item.getPrice(),item.getSize());
                orderItems.add(o);
                orderItemDao.insertOrderItem(o);//插入当前订单项
            }
        }

        OrderItemAdapter orderItemAdapter = new OrderItemAdapter(this,orderItems,mGoodsMap);
        rv_purchaseItem.setAdapter(orderItemAdapter);
        tv_sum = findViewById(R.id.tv_sum);
        tv_sum.setText("￥"+String.valueOf(GoodsDetailActivity.formatDouble(total)));
        tv_total_price = findViewById(R.id.tv_total_price);
        tv_total_price.setText(String.valueOf(GoodsDetailActivity.formatDouble(total)));

        // 切换地址
        iv_xg.setOnClickListener(view -> {
            // 点击跳转到地址管理页面
            Intent intent = new Intent(this, AddressActivity.class);
            intent.putExtra("userId", mUserId); // 根据用户id来进行查询
            intent.putExtra("cartId",mCartId);
            intent.putExtra("change", true);
            intent.putExtra("total",total);
            Bundle bundle2 = new Bundle();
            bundle2.putSerializable("goodsMap", mGoodsMap);
            bundle2.putSerializable("cartItemList", new ArrayList<>(mCartItemList));
            intent.putExtras(bundle2);
            startActivity(intent);
        });

        findViewById(R.id.btn_settle2).setOnClickListener(view -> {
            // 构建 POST 数据
            OrderPostData postData = new OrderPostData(orderToPay, orderItems);

            postOrderToBackend(postData);   // json
            paybill(orderId);
        });




    }





    public void postOrderToBackend(OrderPostData postData) {

        Gson gson = new Gson();
        String postDataJson = gson.toJson(postData);

        OkHttpClient client = new OkHttpClient();
        System.out.println("提交订单到后台");

        RequestBody body = RequestBody.create(
                postDataJson,
                MediaType.parse("application/json; charset=utf-8")
        );


        Request request = new Request.Builder()
                .url("http://172.20.10.12:8080/order") // 后端接口 URL
                .post(body) // POST 请求
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                // 请求失败处理
                e.printStackTrace();
                System.err.println("订单上传失败: " + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 请求成功
                    String responseBody = response.body().string();
                    System.out.println("订单上传成功，返回数据: " + responseBody);
                } else {
                    // 请求失败
                    System.err.println("订单上传失败，HTTP 状态码: " + response.code());
                }
            }
        });
    }

    public void paybill(long orderId){
            String cost = GoodsDetailActivity.formatDouble(total);


            OkHttpClient client = new OkHttpClient();
            String BASE_URL = null;
            System.out.println("订单号为"+(100000+orderId));
            BASE_URL = "http://172.20.10.12:8080/alipay/pay?subject="+123456+"&traceNo="+(100000+orderId)+"&totalAmount="+cost;



            Request request = new Request.Builder()
                           .url(BASE_URL)
                           .get()
                           .build();

                   client.newCall(request).enqueue(new Callback() {
                       @Override
                       public void onFailure(@NonNull Call call, @NonNull IOException e) {
                           System.err.println("支付请求失败: " + e.getMessage());
                       }

                       @Override
                       public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                           if (response.isSuccessful()) {

                               String responseBody = response.body().string();
                               System.out.println("支付页面表单: \n" + responseBody);

                               Intent intent = new Intent(PurcharseActivity.this, PaymentActivity.class);
                               intent.putExtra("paymentHtml", responseBody);
                               intent.putExtra("userId",mUserId);
                               intent.putExtra("cartId",mCartId);
                               intent.putExtra("orderId",orderId);
                               startActivityForResult(intent, REQUEST_CODE_PAYMENT);
                               Log.d(TAG,"订单号为"+orderId);
                           } else {
                               System.err.println("支付请求失败: " + response.message());
                           }
                       }
                   });  // get 请求完毕

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_PAYMENT && resultCode == RESULT_OK) {
            if (data != null) {
                orderId = data.getLongExtra("orderId", 0L);
                System.out.println("返回的订单 ID: " + orderId);
            }
        }
    }


}